package com.example.classwork;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.preference.PreferenceManager;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "Main";
    private float dollarRate = 0f;
    private float euroRate = 0f;
    private float wonRate = 0f;
    private float Result = 0.0f;

    private final Timer timer = new Timer();
    private TimerTask task;

    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView result = findViewById(R.id.result);
        SharedPreferences sharedPreferences = getSharedPreferences("myRate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        dollarRate = sharedPreferences.getFloat("dollar_rate_key", 0.1f);
        euroRate = sharedPreferences.getFloat("euro_rate_key", 0.2f);
        wonRate = sharedPreferences.getFloat("won_rate_key", 123.0f);
        Log.i(TAG, "onCreate: get from sp dollarRate=" + dollarRate);
        Log.i(TAG, "onCreate: get from sp euroRate=" + euroRate);
        Log.i(TAG, "onCreate: get from sp wonRate=" + wonRate);

        Thread t = new Thread(this);

        t.start();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 5) {
                    Bundle bundle = (Bundle) msg.obj;
                    dollarRate = bundle.getFloat("dollar_rate_key2");
                    euroRate = bundle.getFloat("euro_rate_key2");
                    wonRate = bundle.getFloat("won_rate_key2");
                    Log.i(TAG, "handleMessage dollarRate:" + dollarRate);
                    Log.i(TAG, "handleMessage euroRate:" + euroRate);
                    Log.i(TAG, "handleMessage wonRate:" + wonRate);

                    Toast.makeText(MainActivity.this, "汇率已更新", Toast.LENGTH_SHORT).show();
                }
                super.handleMessage(msg);
            }
        };

    }

    public void myClick(View btn) {
        EditText rmb = findViewById(R.id.rmb_inp);
        String str = rmb.getText().toString();


        if (str.length() == 0) {
            Toast.makeText(this, "请输入金额！", Toast.LENGTH_SHORT).show();
            return;
        } else {
            float i = Float.parseFloat(str);
            float r = 0.0f;
        }
        Log.i(TAG, "myClick:");
        if (btn.getId() == R.id.btn_dollar) {
            float i = Float.parseFloat(str);
            Result = i * dollarRate;
        } else if (btn.getId() == R.id.btn_euro) {
            float i = Float.parseFloat(str);
            Result = i * euroRate;

        } else {
            float i = Float.parseFloat(str);
            Result = i * wonRate;
        }
        ((TextView) findViewById(R.id.result)).setText("结果为：" + Result);
    }


    public void open(View btn) {
        Log.i(TAG, "open: Input");
        openInput();
    }

    private void openInput() {
        Intent config = new Intent(this, InputActivity.class);
        config.putExtra("dollar_rate_key", dollarRate);
        config.putExtra("euro_rate_key", euroRate);
        config.putExtra("won_rate_key", wonRate);
        Log.i(TAG, "open: dollarRate=" + dollarRate);
        Log.i(TAG, "open: euroRate=" + euroRate);
        Log.i(TAG, "open: wonRate=" + wonRate);
        startActivityForResult(config, 3);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult: requestCode=" + requestCode);
        Log.i(TAG, "onActivityResult: resultCode=" + resultCode);
        if (requestCode == 3 && resultCode == 6) {
            Bundle bdl = data.getExtras();
            dollarRate = bdl.getFloat("dollar_rate_key1");
            euroRate = bdl.getFloat("euro_rate_key1");
            wonRate = bdl.getFloat("won_rate_key1");
            Log.i(TAG, "onActivityResult: dollarRate=" + dollarRate);
            Log.i(TAG, "onActivityResult: euroRate=" + euroRate);
            Log.i(TAG, "onActivityResult: wonRate=" + wonRate);

            SharedPreferences sp = getSharedPreferences("myRate", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_rate_key", dollarRate);
            editor.putFloat("euro_rate_key", euroRate);
            editor.putFloat("won_rate_key", wonRate);
            editor.apply();
            Log.i(TAG, "onActivityResult: save to sp");
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.myrate, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_setting) {
            openInput();
        }
        return super.onOptionsItemSelected(item);
    }



        @Override
        public void run () {
            Log.i(TAG, "run:Running.......");
            Timer timer = new Timer(true);
        TimerTask task = new TimerTask() {
            @Override
            public void run() {


            /*for (int i = 1; i < 3; i++) {
                Log.i(TAG, "run:i=" + i);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }*/
            Bundle bundle = new Bundle();


      /*URL url = null;
        try {
            url = new URL("https://www.usd-cny.com/bankofchina.htm");
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            InputStream in = http.getInputStream();
            String html = inputStream2String(in);
            Log.i(TAG,"run:html="+html);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

            try {
                Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
                String title = doc.title();
                Log.i(TAG, "run:title=" + title);
                Elements tables = doc.getElementsByTag("table");
                Element table = tables.get(0);
                Elements tds = table.getElementsByTag("td");
                for (int i = 0; i < tds.size(); i += 6) {

                    Element td1 = tds.get(i);
                    Element td2 = tds.get(i + 5);
                    String str1 = td1.text();
                    String str2 = td2.text();

                    Log.i(TAG, "run:" + str1 + "==>" + str2);
                    if ("美元".equals(td1.text())) {
                        bundle.putFloat("dollar_rate_key2", 100f / Float.parseFloat(td2.text()));
                    }
                    if ("欧元".equals(td1.text())) {
                        bundle.putFloat("euro_rate_key2", 100f / Float.parseFloat(td2.text()));
                    }
                    if ("韩元".equals(td1.text())) {
                        bundle.putFloat("won_rate_key2", 100f / Float.parseFloat(td2.text()));
                    }
                }

                handler.postDelayed(this, 86400000);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Message msg = handler.obtainMessage(5);
            //msg.obj = "Hello";
            msg.obj = bundle;
            handler.sendMessage(msg);

        }

        };
        timer.schedule(task,1000,86400000);
}
    private String inputStream2String(InputStream inputStream) throws IOException {
            final int bufferSize = 1024;
            final char[] buffer = new char[bufferSize];
            final StringBuilder out = new StringBuilder();
            Reader in = new InputStreamReader(inputStream, "gb2312");
            while (true) {
                int rsz = in.read(buffer, 0, buffer.length);
                if (rsz < 0)
                    break;
                out.append(buffer, 0, rsz);
            }
            return out.toString();
        }



}



